//
//  EvaluationDetailViewController.m
//  coba-iOS
//
//  Created by 郭四虎 on 15/11/28.
//  Copyright © 2015年 YouKu. All rights reserved.
//

#import "EvaluationDetailViewController.h"

@interface EvaluationDetailViewController ()<UIWebViewDelegate,UIScrollViewDelegate,GDTMobBannerViewDelegate>
{
    NSString *_HTMLstr;
    BOOL _down;
    BOOL _up;
    CGFloat _currentY;
}
@property (weak, nonatomic) IBOutlet UILabel *evaluationTitle;
@property (weak, nonatomic) IBOutlet UIWebView *webview;
@property (weak, nonatomic) IBOutlet UILabel *authorLb;
@property (weak, nonatomic) IBOutlet UILabel *dateLb;
@property (weak, nonatomic) IBOutlet UILabel *replyLb;
@property (weak, nonatomic) IBOutlet UILabel *upLb;
@property (weak, nonatomic) IBOutlet UIButton *upBtnsmall;

@property (weak, nonatomic) IBOutlet UIView *upView;
@property (weak, nonatomic) IBOutlet UIView *adView;
@property (weak, nonatomic) IBOutlet UIView *titleView;

@property (weak, nonatomic) IBOutlet UIButton *upBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *adHeight;

@property (weak, nonatomic) IBOutlet UIImageView *imgView;
@property (strong, nonatomic) GDTMobBannerView *bannerView;

@end

@implementation EvaluationDetailViewController

- (GDTMobBannerView *)bannerView
{
    if (!_bannerView) {
        _bannerView = [[GDTMobBannerView alloc] initWithFrame:CGRectMake(0, 0,
                                                                         GDTMOB_AD_SUGGEST_SIZE_320x50.width*SCALEX,
                                                                         GDTMOB_AD_SUGGEST_SIZE_320x50.height) appkey:GGTID placementId:@"4040318167206164"];
        
        // 设置广告视图的位置 宽与高设置为0即可 该广告视图默认是横竖屏自适应 但需要在旋转时调用orientationChanged 方法
        // Set the frame of advertisement view
        _bannerView.delegate = self;
        _bannerView.currentViewController = self; //设置当前的ViewController
        _bannerView.interval = 30; //【可选】设置刷新频率;默认30秒
        _bannerView.isGpsOn = NO; //【可选】开启GPS定位;默认关闭
        //_bannerView.showCloseBtn = NO; //【可选】展示关闭按钮;默认显示
        _bannerView.isAnimationOn = YES; //【可选】开启banner轮播和展现时的动画效果;默认开启
        
        [_bannerView loadAdAndShow];
    }
    return _bannerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
   //_webview.scalesPageToFit = YES;
    self.title = @"测评详情";
    
    _webview.scrollView.bounces = NO;
    _webview.scrollView.delegate = self;
    [self initData];
    _down = NO;
    _up = NO;
    
    [self.imgView addSubview:self.bannerView];
    [self creatData];
    _headerBack.layer.borderColor = [UIColor lightGrayColor].CGColor;
}

- (void)initData
{
//    _headerBack.layer.borderColor = [UIColor lightGrayColor].CGColor;
//    //星级
//    CGRect frame = _starView.frame;
//    frame.size.width = _gamemodel.game_star.floatValue * frame.size.width/5;
//    _starView.frame = frame;
//    
//    //游戏信息
//    self.gameNameLb.text = _gamemodel.game_name;
//    self.gameSize.text = [NSString stringWithFormat:@"%@M",_gamemodel.game_size];
//    self.gameTypeLb.text = _gamemodel.sort_name;
//    self.companyLb.text = _gamemodel.game_author;
//    
//    NSString *url = [NSString stringWithFormat:@"%@?url=%@",GETICON,_gamemodel.game_icon];
//    [self.gameIconima sd_setImageWithURL:[NSURL URLWithString:url]];
    
    //点赞信息
    if (_model.is_up) {
        if (_model.is_up.integerValue > 0) {
            self.upBtn.selected = YES;
            self.upBtnsmall.selected = YES;
        }else{
            self.upBtn.selected = NO;
            self.upBtnsmall.selected = NO;
        }
    }
}

- (void)replaceStr:(NSString *)aaa with:(NSString *)bbb
{
    if ([_HTMLstr rangeOfString:aaa].location != NSNotFound) {
        _HTMLstr = [_HTMLstr stringByReplacingOccurrencesOfString:aaa withString:bbb];
    }
}

- (void)creatData
{
    NSDictionary *parameters = @{@"id":_model.commentid};
    
    NSString *str;
    if ([ISBUS boolValue]) {
        str = [NSString stringWithFormat:@"%@/port/newsGameDetail",CAR_URL];
    }else{
        str = EVALUATIONDETAIL;
    }
    
    [MyAFN POST:str parameters:parameters block:^(id responseObject) {

        NSDictionary *response = responseObject;
        
        _HTMLstr = [response objectForKey:@"content"];
        
        [self replaceStr:@"&lt;" with:@"<"];
        [self replaceStr:@"&gt;" with:@">"];
        [self replaceStr:@"&amp;" with:@"&"];
        [self replaceStr:@"&nbsp;" with:@" "];
        [self replaceStr:@"&quot;" with:@"\""];
        [self replaceStr:@"href=" with:@""];
//        _HTMLstr = [_HTMLstr stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
//        _HTMLstr = [_HTMLstr stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
//        _HTMLstr = [_HTMLstr stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
//        _HTMLstr = [_HTMLstr stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
//        _HTMLstr = [_HTMLstr stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
//        //去除超链接
//        _HTMLstr = [_HTMLstr stringByReplacingOccurrencesOfString:@"href=" withString:@""];
        //设置图片宽度
//        _HTMLstr = [_HTMLstr stringByReplacingOccurrencesOfString:@"max-width: 600px" withString:[NSString stringWithFormat:@"max-width: %fpx",_webview.frame.size.width - 20]];
        
        [_webview loadHTMLString:_HTMLstr baseURL:nil];
        
        _evaluationTitle.text = [response objectForKey:@"title"];
        _dateLb.text = [response objectForKey:@"date"];
        _authorLb.text = [response objectForKey:@"name"];
        _replyLb.text = [response objectForKey:@"reply_num"];
        _upLb.text = [response objectForKey:@"up_num"];
    }error:^(NSError *error) {
        
    }fromController:self];
}
- (IBAction)clickUp:(UIButton *)sender {
    
    if (![Myuser sharedUser].login_id) {
        [self.view Message:@"请登录" HiddenAfterDelay:1];
        return;
    }
    
    if (sender.selected) {
        
        [self.view Message:@"已经赞过" HiddenAfterDelay:1];
        return;
    }
    
    NSDateFormatter *formater = [[NSDateFormatter alloc]init];
    [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *date = [formater stringFromDate:[NSDate date]];
    
    NSDictionary *parameters = @{@"obj_id":_model.commentid,@"is_up_down":@(0),@"user_id":[Myuser sharedUser].login_id,@"date":date};
    
    
    [MyAFN POST:UpDown parameters:parameters block:^(id responseObject) {
        
        NSDictionary *response = responseObject;
        
        if ([[response objectForKey:@"status"]integerValue]==1) {
            [self.view Message:@"点赞成功" HiddenAfterDelay:1];
//            Message(@"点赞成功");
//            [self performSelector:@selector(Message:) withObject:<#(nullable id)#> afterDelay:<#(NSTimeInterval)#>]
            self.upLb.text = [NSString stringWithFormat:@"%ld",self.upLb.text.integerValue + 1];
            self.upBtn.selected = YES;
            self.upBtnsmall.selected = YES;
            
            _model.up_num = [NSString stringWithFormat:@"%ld",_model.up_num.integerValue + 1];
            _model.is_up = [NSString stringWithFormat:@"%ld",_model.is_up.integerValue+1];
            self.updateModel();
            
        }else if ([[response objectForKey:@"status"]isEqualToString:@"005"]){
            
            [[Myuser sharedUser]cleanUser];
            [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userid"];
            [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userpwd"];
            [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"username"];
            [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"usericon"];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"changeUserinfo" object:nil];
            
        }else{
            NSLog(@"%@",[response objectForKey:@"msg"]);
        }
        
    }error:^(NSError *error) {
        
    }fromController:nil];
    
}



- (IBAction)clickReply:(UIButton *)sender {
//    EvaluationReplyViewController *controller = [[EvaluationReplyViewController alloc]init];
//    controller.model = _model;
//    controller.refresh = ^{
//        
//        _replyLb.text = [NSString stringWithFormat:@"%ld",_replyLb.text.integerValue + 1];
//        _model.reply_num = [NSString stringWithFormat:@"%ld",_model.reply_num.integerValue + 1];
//        self.updateModel();
//    };
//    [self.navigationController pushViewController:controller animated:YES];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//    static  NSString * const jsGetImages =
//    
//    @"function getImages(){\
//    var objs = document.getElementsByTagName(\"img\");\
//    for(var i=0;i<objs.length;i++){\
//    objs[i].onclick=function(){\
//    document.location=\"myweb:imageClick:\"+this.src;\
//    };\
//    };\
//    return objs.length;\
//    };";
//    
//    [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
//    
//    //注入自定义的js方法后别忘了调用 否则不会生效（不调用也一样生效了，，，不明白）
//    [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
//    NSString *jsimage = [NSString stringWithFormat:
//    @"function getImages(){\
//    var objs = document.getElementsByTagName(\"img\");\
//    for(var i=0; i<objs.length;i++){\
//    objs[i].style.width= \"%fpx\";\
//    }\
//    }",WIDTH];
//    
//    [webView stringByEvaluatingJavaScriptFromString:jsimage];
//    
//    [webView stringByEvaluatingJavaScriptFromString:@"getImages"];
          NSString * jsGetImages = [NSString stringWithFormat:
    
        @"function getImages(){\
        var objs = document.getElementsByTagName(\"img\");\
        for(var i=0;i<objs.length;i++){\
        objs[i].style.width = \"%fpx\";\
        };\
        \
        };",WIDTH-20];
    
        [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
    
        //注入自定义的js方法后别忘了调用 否则不会生效（不调用也一样生效了，，，不明白）
        [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
}
- (IBAction)delAD:(id)sender {
//    CGRect up = _upView.frame;
//    CGRect ad = _adView.frame;
//    
//    up.origin.y += ad.size.height;
//    _upView.frame = up;
//    [_adView removeFromSuperview];
    [UIView animateWithDuration:0.3 animations:^{
        //广告位下移
        _adHeight.constant -= 55.f*SCALEX;
    }];
    
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    _currentY = scrollView.contentOffset.y;
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y > _currentY) {
        //下移
        if (!_down) {
            _titleHeight.constant -=64.f;
            [UIView animateWithDuration:0.3 animations:^{
                
                [self.view layoutIfNeeded];
            }];
            _down = YES;
            _up = NO;
        }
    }else{
        //上移
        if (!_up) {
            _titleHeight.constant +=64.f;
            [UIView animateWithDuration:0.3 animations:^{
                
                [self.view layoutIfNeeded];
            }];
            
            _up = YES;
            _down = NO;
        }
    }
    
}
- (void)bannerViewFailToReceived:(NSError *)error
{
    
}
- (void)bannerViewWillClose
{
    [UIView animateWithDuration:0.3 animations:^{
        //广告位下移
        _adHeight.constant -= 50.f;
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
